package com.config;

import com.untils.JwtUtil;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 请求头
     */
    private static final String HEADER_AUTH = "Authorization";

    /**
     * 安全的url,无需令牌
     */
    private static final List<String> SAFE_URL_LIST = Arrays.asList("/user/login", "/user/register", "/", "/index", "/user/hasRegister", "/JWTTest/sendCode", "/JWTTest/checkCode", "/user/forget", "/admin/list", "/admin/login", "/user/autoLoad", "/visit/list", "/visit/update", "/visit/selectlist", "/cashier/login", "/cashier/liquidation", "/cashier/updateP");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return true;
//        response.setContentType("application/json; charset=utf-8");
//
//        String url = request.getRequestURI().substring(request.getContextPath().length());
//        System.out.println("url:" + url);
//
//        // 从请求头里面读取token
//        String token = request.getHeader(HEADER_AUTH);
//        System.out.println("取到token:" + token);
//        if (token == null) {
//            // 登录和注册等请求不需要令牌
//            if (SAFE_URL_LIST.contains(url)) {
//                System.out.println("进入白名单");
//                return true;
//            }
//
//            throw new RuntimeException("请求失败，令牌为空");
//        }
//        // 解析令牌
//        System.out.println("准备解析令牌");
//        Map<String, Object> map = JwtUtil.resolveToken(token);
//        try {
//            Long mobile = Long.parseLong(map.get("mobile").toString());
//            ContextHolder.setMobile(mobile);
//            System.out.println("解析无误-mobile:" + mobile);
//        } catch (Exception e) {
//            System.out.println("解析无误-不解析");
//        }
//        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object andler, @Nullable Exception e) {
        ContextHolder.shutdown();
    }
}
